package uqbar.comm;

import java.io.ByteArrayInputStream;
import java.util.Arrays;

import uqbar.comm.protocol.InputBuilder;
import uqbar.comm.protocol.InputFactory;
import uqbar.comm.protocol.InputProcessor;


public class CallerInput<Input> extends InputFactoryDecorator<Input> {

	private Caller<Input> caller;
	private final InputBuilder builder;

	protected CallerInput(final InputFactory<Input> decorated, final Caller<Input> caller, final InputBuilder builder) {
		super(decorated);
		this.caller = caller;
		this.builder = builder;
	}

	@Override
	public Input create(final String type, final byte[] content) {
		if (Caller.CALLER_TYPE.equals(type)) {
			Integer id = new Integer(new String(Arrays.copyOf(content, Caller.ID_SIZE)));
			byte[] internalInput = Arrays.copyOfRange(content, Caller.ID_SIZE, content.length);
			CallerInputProcessor callerInputProcessor = new CallerInputProcessor();
			this.builder.read(new ByteArrayInputStream(internalInput), this.getDecorated(), callerInputProcessor);
			this.caller.setResponse(id, callerInputProcessor.getResponse());
			return callerInputProcessor.getResponse();
		} else {
			return super.create(type, content);
		}
	}

	protected class CallerInputProcessor implements InputProcessor<Input> {

		private Input response;

		@Override
		public void process(final Input input) {
			this.response = input;
		}

		public Input getResponse() {
			return this.response;
		}

	}
}
